import { 
        GET_COUPON_LIST,
        GET_COUPON_INFO,
        GET_ORG_LIST,
        GET_COUPON_PRODUCT_LIST,
        EDIT_COUPON 
    } from '../../constants/ActionTypes'
import { treeDataFormat } from '../../utils/TreeUtil'


const initialState = {
    couponList: [],
    couponListTotal: 0,
    couponInfo:{},
    orgList:[],
    couponProductList:[],
    editCouponStatus:false,//编辑优惠券状态
}


const couponReducer = (state = initialState, action) =>{ 
    switch (action.type){
        case GET_COUPON_LIST: 
            let obj = {};
            obj.couponList = action.couponList?action.couponList:[];
            obj.couponListTotal = action.couponListTotal?action.couponListTotal:0;
            return Object.assign({},state,obj);   
        case GET_COUPON_INFO:          
            if(!state.couponInfo.hasOwnProperty(action.id)){
                let _couponInfoObj = Object.assign({},state.couponInfo,{
                    [action.id]:[{...action.couponInfo,key:action.id}]
                })
                return Object.assign({},state,{                    
                    couponInfo: _couponInfoObj
                });
            }
            break;
        case GET_ORG_LIST:
            let _orgObj = {
                orgList:treeDataFormat(action.orgList.map((item)=>(
                    {
                        ...item,
                        label:item.name,
                        value:item.id
                    }
                )),"no", "pno",'children')
            };
            return Object.assign({},state,_orgObj)
        case GET_COUPON_PRODUCT_LIST:
            return Object.assign({},state,{
                couponProductList:action.couponProductList
            })
        case EDIT_COUPON:
        return Object.assign({},state,{
            editCouponStatus:action.editCouponStatus
        })            
        default:
            return {...state}
   }
}

export const couponList = (state) => state.couponList

export const couponTotal = (state) => state.couponListTotal

export const couponInfo = (state) => state.couponInfo

export const orgList = (state) => state.orgList

export const couponProductList = (state) => state.couponProductList

export const editCouponStatus = (state) => state.editCouponStatus


export default couponReducer
